package pictureRater;

import java.text.DecimalFormat;

import gen.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

/**
* <p>Title: MainActivity Class</p>
* <p>Description: CSIS 343 Course Project</p>
* @author Peter Tschida, Nicholas Seehafer, Jim Stevens, Nickolas Wait
* @email peter.tschida@my.uwrf.edu, nicholas.seehafer@my.uwrf.edu, james.stevens@my.uwrf.edu, nickolas.wait@my.uwrf.edu
* @date November 2011
* @team Group 6
*/
public class MainActivity extends Activity {
	
	ViewFlipper vf; 
	ViewFlipper flipImage;
	private static final int SELECT_PICTURE = 1;
	
	
    /** 
     * Called when the activity is first created
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        setContentView(R.layout.main);
        vf = (ViewFlipper) findViewById(R.id.vf);
        flipImage = (ViewFlipper)findViewById(R.id.flipImage);
        
        setLoginClickListener();
        setBackButtonListener();
        setBrowseButtonListener();
        setBack2ButtonListener();
        setAboutButtonListener();
        setBack3ButtonListener();
        setUploadButtonListener();
        setBack4ButtonListener();
        setEditButtonListener();
        setBack5ButtonListener();
        setAdminButtonListener();
        setAdminLoginClickListener();
        setAdminLogoutListener();
        setBack6ButtonListener();
        setRatingBarListener();
        setNextButtonListener();
        setPreviousButtonListener();
        setCommentButtonListener();
        setSelectButtonListener();
        setAddImageButtonListener();
        setRotateButtonListener();
        setSendBrowseButtonListener();
    }
    
    /**
     * on click listener for the login button
     * flip to next view (menu) if user enters a username and clicks login button
     * show message"Enter name please!" if user does not enter a username and clicks login
     */
    private void setLoginClickListener(){
        Button LoginButton = (Button)findViewById(R.id.loginbutton);
        LoginButton.setOnClickListener(new View.OnClickListener() {
        	
			public void onClick(View v) {
				EditText username = (EditText)findViewById(R.id.usernametext);
			//check if the user entered something into textview
			if(username.length() > 0){
				vf.showNext();
			}else {
				Toast.makeText(MainActivity.this, "Enter name please! ", Toast.LENGTH_SHORT).show();	
			}
			}
		});
    }
    
    
    /**
     * on click listener for back button on menu
     * if clicked go back to login screen
     */
    private void setBackButtonListener(){
    	Button BackButton = (Button)findViewById(R.id.backbutton);
    	BackButton.setOnClickListener(new View.OnClickListener() {
			
			//if user clicks logout, confirm and logout or cancel
			public void onClick(View v) {
				AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
				builder.setMessage("Are you sure you want to logout?")
				.setTitle("Are you sure?")
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						EditText usernametext = (EditText)findViewById(R.id.usernametext);
						usernametext.setText("");
						vf.showPrevious();
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
							dialog.cancel();

					}
				});
				builder.create().show();
				
			}
		});
    }
    
    /**
     * on click listener for browse button
     * go to browse view if clicked
     */
    private void setBrowseButtonListener(){
    	Button BrowseButton = (Button)findViewById(R.id.browsebutton);
    	BrowseButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
	
				vf.showNext();
				
			}
		});
    }
    
    /**
     * on click listener for back(menu) button in browse view
     * go back to menu if clicked
     */
    private void setBack2ButtonListener(){
    	 Button BackButton2 = (Button)findViewById(R.id.buttonbutton2);
    	 BackButton2.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showPrevious();
			}
		});
    }
   
    /**
     * on click listener for about button
     * go to about view if clicked
     */
    private void setAboutButtonListener(){
    	 Button AboutButton = (Button)findViewById(R.id.aboutbutton);
    	 AboutButton.setOnClickListener(new View.OnClickListener() {
    		
    		 
			public void onClick(View v) {
				vf.showNext();
				vf.showNext();
				 TextView about =(TextView)findViewById(R.id.abouttext);
				about.setText("Beard and Mustache Rater is uploaded daily" +
						" with beards and mustaches from our users. With" +
						" Beard and Mustache Rater, you can rate beards and" +
						" mustaches, comment on beards and mustaches, and" +
						" upload your own!");
				
			}
		});
    }
   
    /**
     * on click listener for back(menu) button in about view
     * go to menu view if clicked
     */
    private void setBack3ButtonListener(){
    	Button BackButton3 = (Button)findViewById(R.id.backbutton3);
    	BackButton3.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showPrevious();
				vf.showPrevious();
			}
		});
    }
    
    /**
     * on click listener for the upload button
     * go to upload view if clicked
     */
    private void setUploadButtonListener(){
    	Button UploadButton = (Button)findViewById(R.id.uploadbutton);
    	UploadButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showNext();
				vf.showNext();
				vf.showNext();
			}
		});
    }
    
    /**
     * on click listener for back(menu) button in about upload view
     * go to menu if clicked
     */
    private void setBack4ButtonListener(){
    	Button BackButton4 = (Button)findViewById(R.id.backbutton4);
    	BackButton4.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
			}
		});
    }
  
    /**
     * on click listener for the edit button
     * go to edit view if clicked
     */
    private void setEditButtonListener(){
    	Button EditButton = (Button)findViewById(R.id.editbutton);
    	EditButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showNext();
				vf.showNext();
				vf.showNext();
				vf.showNext();
			}
		});
    }
  
    /**
     * on click listener for back(menu) button in about upload view
     * go to menu if clicked
     */
    private void setBack5ButtonListener(){
    	Button BackButton5 = (Button)findViewById(R.id.backbutton5);
    	BackButton5.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
			}
		});
    }
  
    /**
     * on click listener for admin button in the login view
     * go to admin login view if clicked
     */
    private void setAdminButtonListener(){
    	Button AdminButton = (Button)findViewById(R.id.adminbutton);
    	AdminButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				vf.showNext();
				vf.showNext();
				vf.showNext();
				vf.showNext();
				vf.showNext();
				vf.showNext();
				
			}
		});
    }
    
    /**
     * on click listener for the admin login button in the admin login view
     * if the text field is equal to password go to admin browse view
     * if the text field is not equal to password show "Incorrect password!" message
     */
    private void setAdminLoginClickListener(){
        Button AdminLoginButton = (Button)findViewById(R.id.adminloginbutton);
        AdminLoginButton.setOnClickListener(new View.OnClickListener() {
        	
			public void onClick(View v) {
				EditText adminusername = (EditText)findViewById(R.id.adminusername);
				
				String password = "fastgreensheep";
				String input = adminusername.getText().toString();
			if(input.equals(password)){
				vf.showNext();
				
			}else {
				Toast.makeText(MainActivity.this, "Incorrect password! ", Toast.LENGTH_SHORT).show();	
			}
			}
		});
    }

    /**
     * on click listener for logout button in admin browse view
     * go to login view if clicked
     */
    private void setAdminLogoutListener(){
    	Button AdminLogutButton = (Button)findViewById(R.id.adminlogout);
    	AdminLogutButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				EditText adminusername = (EditText)findViewById(R.id.adminusername);
				adminusername.setText("");
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
			}
		});
    }
    /** listener for the menu(back) button in admin login view
     * 
     */
    private void setBack6ButtonListener(){
    	Button backButton6 = (Button)findViewById(R.id.backbutton6);
    	backButton6.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
				vf.showPrevious();
			}
		});
    }
    
    
    /** listener for the rating bar
     * 
     */
    private void setRatingBarListener(){
    	RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar1);
    	 final TextView textRating = (TextView) findViewById(R.id.textRating);

    	
    	ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
    		double avgRating = 0, total =0; 
    		int num = 0, count =0;
    		
    		//display the average rating after each change in rating bar
    		public void onRatingChanged(RatingBar ratingBar, float rating,
    			boolean fromUser) {
    			
    			if(count <1){
    				double Rating = (double)ratingBar.getRating();
    				total = Rating + total;
    				num = num +1;
    				avgRating = total/num;
    				avgRating = round(avgRating);
    				textRating.setText(String.valueOf(avgRating));
    				count++;
    				
    			}
    			ratingBar.setRating((float) avgRating);
    		}
    	});
    	
    }
    /**
     * change image in the browse view to next image when next button is clicked
     */
    private void setNextButtonListener(){
    	Button nextButton = (Button)findViewById(R.id.nextbutton);
    	nextButton.setOnClickListener(new View.OnClickListener() {
		
			
			public void onClick(View v) {
				 setRatingBarListener();
				RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar1);
				final TextView textRating = (TextView) findViewById(R.id.textRating);
				final TextView textComment = (TextView) findViewById(R.id.textcomment);
				
				//change the image to the next image
	
					flipImage.showNext();
				
				
		    	 
				//reset the rating bar, average rating, and comments
		    	 ratingBar.setRating(0);
		    	 textRating.setText("");
		    	 textComment.setText("");
		    	 setRatingBarListener();
			}
		});
    }
    /** change image in the browse view to the previous image when previous button is clicked
     * 
     */
    private void setPreviousButtonListener(){
    	Button previousButton = (Button)findViewById(R.id.previousbutton);
    	previousButton.setOnClickListener(new View.OnClickListener() {
			
    		
			public void onClick(View v) {
				setRatingBarListener();
				RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar1);
		    	 final TextView textRating = (TextView) findViewById(R.id.textRating);
		    	 final TextView textComment = (TextView) findViewById(R.id.textcomment);
		    	 
		    	 //change the image to the previous image
		    	 flipImage.showPrevious();
		    	 
		    	 //reset the rating bar, average rating, and comments
		    	 ratingBar.setRating(0);
		    	 textRating.setText("");
		    	 textComment.setText("");
		    	 setRatingBarListener();
				 
			}
		});
    }
    
    /**open alertDialog with edit text view, then append the comment to textComment TextView
     * 
     */
    private void setCommentButtonListener(){
    	Button CommentButton = (Button)findViewById(R.id.commentbutton);
        final TextView textComment = (TextView) findViewById(R.id.textcomment);
        final EditText username = (EditText)findViewById(R.id.usernametext);
        
    	CommentButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				 AlertDialog.Builder commentDialog = new AlertDialog.Builder(MainActivity.this);  
				         
				 commentDialog.setTitle("Comment");  
				 commentDialog.setMessage("Comment on picture:");  
				           
				 // Set an EditText view to get user input   
				 final EditText input = new EditText(MainActivity.this);  
				 commentDialog.setView(input); 

				         commentDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				        {  
				                public void onClick(DialogInterface dialog, int whichButton)
				                {  
				                	String user = username.getText().toString();
				                	
				              textComment.append(user+":'"+input.getText()+"'\n");
				              
				              
				          }  
				        });  
				          
				         commentDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {  
				          public void onClick(DialogInterface dialog, int whichButton) {  
				            // Canceled.  
				          }  
				        });  
				          
				         commentDialog.show();
				
			}
		});
    }
    
    /**Listener for select image button
     * 
     */
    private void setSelectButtonListener(){
		Button BrowseButton= (Button) findViewById(R.id.Button01);
		BrowseButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,
                        "Select Picture"), SELECT_PICTURE);
				
			}
		});
	}
   
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	
		String selectedImagePath;
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
	            
	            ImageView UploadImage = (ImageView)findViewById(R.id.image1);
	            UploadImage.setImageBitmap(bitmap);
	            

	        }
	    }
	}
    
	/**return the path of the picture that the cursor is on
	 * @param uri
	 * @return cursor.getString(column_index)
	 */
	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor
	            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
	
	 /**listener for add image button in upload view 
	 * 
	 */
	private void setAddImageButtonListener(){
	    	Button BrowseButton = (Button)findViewById(R.id.sendeditbutton);
	    	BrowseButton.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
					
					 //ImageView Image = (ImageView)findViewById(R.id.image1);
					
					ImageView UploadImage = (ImageView)findViewById(R.id.image1);
		            
					UploadImage.buildDrawingCache();
		            Bitmap bmap = UploadImage.getDrawingCache();
		            
		            //set the image view in edit view
		            ImageView EditImage = (ImageView)findViewById(R.id.editimage);
		            EditImage.setImageBitmap(bmap); 
					Toast.makeText(MainActivity.this, "Image sent to edit.", Toast.LENGTH_SHORT).show();
					
				}
			});
	    }
	/**button listener for rotate button in edit view
	 * 
	 */
	private void setRotateButtonListener(){
    	Button RotateButton = (Button)findViewById(R.id.rotatebutton);
    	
    	RotateButton.setOnClickListener(new View.OnClickListener() {
		
			public void onClick(View v) {
				ImageView EditImage = (ImageView)findViewById(R.id.editimage);
				EditImage.buildDrawingCache();
	            Bitmap bmap = EditImage.getDrawingCache();
	            
	            int width = bmap.getWidth();
	            int height = bmap.getHeight();
	            
	            Matrix matrix = new Matrix();
	            matrix.postRotate(90, bmap.getWidth(), bmap.getHeight());
	           
	           
	            Bitmap rotatedBM = Bitmap.createBitmap(bmap, 0, 0,width, height,matrix, true);
	            
	            EditImage.setImageBitmap(rotatedBM);
	            
	            
			}
			
		});
    }
	private void setSendBrowseButtonListener(){
    	Button BrowseButton = (Button)findViewById(R.id.sendbrowsebutton);
    	BrowseButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
		
				ImageView editImage = (ImageView)findViewById(R.id.editimage);
				ImageView Image6 = (ImageView)findViewById(R.id.image6);
				
				
				editImage.buildDrawingCache();
	            Bitmap bmap = editImage.getDrawingCache();
				Image6.setImageBitmap(bmap);
	            
				
				Toast.makeText(MainActivity.this, "Image added to browse pictures.", Toast.LENGTH_SHORT).show();
				
			}
		});
    }

    /** used to format double value to two decimal places
     * @param d
     * @return Double.valueOf(twoDForm.format(d)
     */
    private double round(double d) {
        DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double.valueOf(twoDForm.format(d));
}
     
}

